了解Cloud Firestore的運作後,終於要使用Xcode存取使用者資料了!以下介紹Xcode中常用的Cloud Firestore存取,其中包含儲存、讀取和刪除資料的方式
參考資料:https://firebase.google.com/docs/firestore/quickstart?authuser=4#ios_1
點擊Xcode專案資料夾中的「Podfile」檔案,確認是否有「pod 'Firebase/Firestore'」
開啟「(專案名稱).xcworkspace」檔案,點擊想要使用功能的swift檔,於檔案最上方輸入「import Firebase」,並於class中輸入「let db = Firestore.firestore()」
import Firebase
//class ViewController: UIVViewController {
let db = Firestore.firestore()
// ...
//}
(1) 設定集合為指定位置
let usersCollectionRef = db.collection("users")
(2) 設定集合中的文件為指定位置
let alovelaceDocumentRef = db.collection("users").document("alovelace")
(3) 設定子集合中的文件為指定位置
let messageRef = db.collection("rooms").document("roomA").collection("messages").document("message1")
(1) 建立文件
// Add a new document in collection "cities"
db.collection("cities").document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA"
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
(2) 添加文件資料
// Update one field, creating the document if it does not exist.
db.collection("cities").document("LA").setData([ "capital": true ], merge: true)
(3) 建立自動生成文件ID的資料
// Add a new document with a generated id.
var ref: DocumentReference? = nil
ref = db.collection("cities").addDocument(data: [
"name": "Tokyo",
"country": "Japan"
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
(4) 更新文件
// update the "capital" field of the city 'LA'
db.collection("cities").document("LA").updateData([
"capital": false
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
(1) 讀取單個文件
let docRef = db.collection("cities").document("LA")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
(2) 讀取集合中的所有文件
db.collection("cities").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
(1) 刪除文件
db.collection("cities").document("LA").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
(2) 刪除文件資料
db.collection("cities").document("LA").updateData([
"capital": FieldValue.delete(),
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}